﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Collections.Generic;

namespace JWTAlgorithm
{
    class Program
    {
        /// <summary>
        /// JWT 中Toke 数据解析地址：https://jwt.io/
        /// </summary>


        private static string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk";//不要泄露
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
           string token= JWTCompute();
            Console.WriteLine(token);
            UnJWTCompute(token);
            Console.ReadKey();
        }

        /// <summary>
        /// JWT加密
        /// </summary>
        /// <returns></returns>
        public static string JWTCompute()
        {
            var payload = new Dictionary<string, object> {
                    { "UserId", 123 },
                    { "UserName", "admin" } };
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            return encoder.Encode(payload, secret);
        }

        /// <summary>
        /// JWT解密
        /// </summary>
        /// <param name="token"></param>
        public static void UnJWTCompute(string token)
        {
            try
            {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                // var json = decoder.Decode(token);
                var json = decoder.Decode(token+"232", secret, verify: true); //对数据进行校验
                Console.WriteLine(json);
            }
            catch (FormatException)
            {
                Console.WriteLine("Token format invalid");
            }
            catch (TokenExpiredException)
            {
                Console.WriteLine("Token has expired");
            }
            catch (SignatureVerificationException)
            {
                Console.WriteLine("Token has invalid signature");
            }
        }
    }
}
